var jwt = require("jsonwebtoken");
var axios = require("axios");
var xml2js = require("xml2js");

module.exports = class extends think.Controller {
  async __before() {
    try {
      this.xcxip = this.ctx.header["x-real-ip"] || "127.0.0.1";
    } catch (e) {
      this.xcxip = "127.0.0.1";
    }

    this.assign({
      base_url: "/www/static/",
      dxgwurl:
        "https://duxinggj-1251133427.cos.ap-guangzhou.myqcloud.com/dxgjgw/",
      abbQz: "https://duxinggj-1251133427.cos.ap-guangzhou.myqcloud.com/abb/",
      djhsRoot: "/djhs/",
      djhsQz:
        "https://duxinggj-1251133427.cos.ap-guangzhou.myqcloud.com/djhs/news/",
    });
  }
  /**生成token
   * @param data= 要加密的对象
   * @return token
   **/
  generateTheToken(data, gq) {
    let obj = {};
    obj.data = data || {}; //存入token的数据
    obj.ctime = new Date().getTime(); //token的创建时间
    obj.expiresIn = gq || 1000 * 60 * 60 * 12; //设定的过期时间
    var token = jwt.sign(obj, this.config("secretKeytoken"));
    return token;
  }

  /*解析token
     * @param text = token字符串
     * @return 解析后的token对象
     示例
     await cn.analysisToken('token')
     */
  analysisToken(token) {
    if (!token) {
      return;
    }
    return new Promise((resolve, reject) => {
      let result = null;
      try {
        let { data, ctime, expiresIn } = jwt.verify(
          token,
          this.config("secretKeytoken")
        );
        let nowTime = new Date().getTime();
        if (nowTime - ctime < expiresIn) {
          result = data;
        }
      } catch (error) {
        console.log(error);
      }
      if (result) {
        resolve(result);
      } else {
        resolve("");
      }
    });
  }
  async getzd(key) {
    const webConfig = this.model("webConfig");
    const xwb = await webConfig.zdseql(key);
    const data = xwb[0];
    if (!data) {
      return false;
    }
    if (data.type == 3) {
      data.text = data.text.split(",");
    }
    if (data.type == 5) {
      data.text = JSON.parse(data.text);
    }
    return data.text;
  }
  dxPost(urls, data, headers) {
    return new Promise((resolve, reject) => {
      axios({
        method: "post",
        url: urls,
        data: data,
        headers: headers,
      })
        .then((res) => {
          resolve(res.data);
        })
        .catch((res) => {
          console.log(res);
          const ress = "" + res;
          resolve(ress);
        });
    });
  }
  dxGet(urls, data, headers) {
    return new Promise((resolve, reject) => {
      axios
        .get(urls, {
          params: data,
          headers: headers,
        })
        .then(function (response) {
          resolve(response.data);
        })
        .catch((res) => {
          console.log(res);
          const ress = "" + res;
          resolve(ress);
        });
    });
  }
  timeCycle(t) {
    let time = new Date();
    if (t) {
      time = new Date(t);
    }
    let Year = time.getFullYear(),
      Month = time.getMonth() + 1,
      Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
      hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
      Minutes =
        time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
      Seconds =
        time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
    Month < 10 ? (Month = 0 + "" + Month) : "";
    return `${Year}-${Month}-${Data} ${hour}:${Minutes}:${Seconds}`;
  }
  timeCycledata(t) {
    let time = new Date();
    if (t) {
      time = new Date(t);
    }
    let Year = time.getFullYear(),
      Month = time.getMonth() + 1,
      Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
      hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
      Minutes =
        time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
      Seconds =
        time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
    Month < 10 ? (Month = 0 + "" + Month) : "";
    return `${Data}`;
  }

  timeCyclenyrh(t) {
    let time = new Date();
    if (t) {
      time = new Date(t);
    }
    let Year = time.getFullYear(),
      Month = time.getMonth() + 1,
      Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
      hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
      Minutes =
        time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
      Seconds =
        time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
    Month < 10 ? (Month = 0 + "" + Month) : "";
    return `${Year}-${Month}-${Data}`;
  }
  timeCyclenyr(t) {
    let time = new Date();
    if (t) {
      time = new Date(t);
    }
    let Year = time.getFullYear(),
      Month = time.getMonth() + 1,
      Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate(),
      hour = time.getHours() < 10 ? 0 + "" + time.getHours() : time.getHours(),
      Minutes =
        time.getMinutes() < 10 ? 0 + "" + time.getMinutes() : time.getMinutes(),
      Seconds =
        time.getSeconds() < 10 ? 0 + "" + time.getSeconds() : time.getSeconds();
    Month < 10 ? (Month = 0 + "" + Month) : "";
    return `${Year}-${Month}`;
  }
  isgq(t) {
    let time = new Date(t).getTime();
    let ntime = new Date().getTime();
    let jnmxsf = false;
    if (ntime > time) {
      jnmxsf = true;
    }
    return jnmxsf;
  }
  /*json对象转字符串*/
  jsonToString(data) {
    let string = "";
    try {
      const _result = [];
      for (const key in data) {
        const value = data[key];
        if (value.constructor == Array) {
          value.forEach(function () {
            _result.push(key + "=" + value);
          });
        } else {
          _result.push(key + "=" + value);
        }
        string = _result.join("&");
      }
    } catch (e) {
      console.log(e);
    }
    return string;
  }
  timeCycleer(t) {
    let time = new Date();
    if (t) {
      time = new Date(t);
    }
    let Year = time.getFullYear(),
      Month = time.getMonth() + 1,
      Data = time.getDate() < 10 ? 0 + "" + time.getDate() : time.getDate();
    Month < 10 ? (Month = 0 + "" + Month) : "";
    return `${Year}-${Month}-${Data}`;
  }
  async chat(text) {
    let openapi = {},
      perception = {},
      userInfo = {
        apiKey: "d4bde20ccee24512a01556ac8fdf9781",
        userId: "demo",
      };
    perception.inputText = {};
    perception.inputText.text = text;
    openapi.reqType = 0;
    openapi.perception = perception;
    openapi.userInfo = userInfo;
    let res = await this.dxPost(
      "http://openapi.tuling123.com/openapi/api/v2",
      openapi
    );
    let dats = {};
    dats.code = 0;
    dats.data = res.results[0].values.text;
    return dats;
  }
  async chatGpt(text) {
    const res = await this.dxGet("http://47.254.71.54:8360", {
      text,
    });
    return res;
  }

  /**
   * @param len 随机数的长度
   * @return 随机数
   **/
  randomString(len) {
    len = len || 32;
    var $chars =
      "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = "";
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  buildXML(json) {
    var builder = new xml2js.Builder();
    return builder.buildObject(json);
  }
  parseXML(xml, fn) {
    var parser = new xml2js.Parser({
      trim: true,
      explicitArray: false,
      explicitRoot: false,
    });
    parser.parseString(xml, fn || function (err, result) {});
  }
  zx(data) {
    var stringA = Object.keys(data),
      s_sdfs = "";
    stringA.map(function (a) {
      s_sdfs += "&" + a + "=" + data[a];
    });
    s_sdfs = s_sdfs.substring(1, s_sdfs.length);
    return s_sdfs;
  }
};
